<?php

namespace App\Models;

use App\ModelFilters\Qh_CdkeyFilter;
use DB;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Qh_Cdkey extends BaseModel
{
    protected $table = 'qh_cdkeys';

    protected $guarded = [];

    protected $appends = ['activeCourse'];

    public function modelFilter(): ?string
    {
        return $this->provideFilter(Qh_CdkeyFilter::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'userId');
    }

    public function course(): BelongsTo
    {
        return $this->belongsTo(Qh_Course::class, 'courseId');
    }

    public function getActiveCourseAttribute()
    {
        if (!$this->activeCourseId) return null;
        return Qh_Course::find($this->activeCourseId)->only(['id', 'name']);
    }

    public function group(): BelongsTo
    {
        return $this->belongsTo(Qh_CdkeyGroup::class, 'groupId');
    }

    protected static function boot()
    {

        parent::boot();

        // 删除的时候删除用户的学科
        static::deleting(function ($model) {
            DB::table('qh_user_has_course')->where('sourceId', $model->id)->where('type', 2)->where('courseId', $model->activeCourseId)->delete();

            // 变更group的数量
            $cdkeyGroup = Qh_CdkeyGroup::find($model->groupId);
            if ($cdkeyGroup) {
                $cdkeyGroup->count = $cdkeyGroup->count - 1;
                $cdkeyGroup->save();
            }
        });
    }
}
